package com.lanou3g.zjl.chating.home.message;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Filter;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.toolbox.NetworkImageView;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.exceptions.EaseMobException;
import com.lanou3g.zjl.chating.R;
import com.lanou3g.zjl.chating.home.chatwindow.ChatWindowActivity;
import com.lanou3g.zjl.chating.home.friends.EaseUser;
import com.lanou3g.zjl.chating.utils.DataChange;
import com.lanou3g.zjl.chating.utils.EaseCommonUtils;
import com.lanou3g.zjl.chating.utils.OnItemClickListener;
import com.lanou3g.zjl.chating.utils.OnTouchListener;
import com.lanou3g.zjl.chating.utils.SmileUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by dllo on 15/11/19.
 */
public class ConversationRvAdapter extends RecyclerView.Adapter<ConversationRvAdapter.ConversationViewHolder> {
    private List<EMConversation> conversationList;
    private List<EMConversation> searchConversationList; // 搜索得到的列表
    private ConversationFilter conversationFilter;
    private OnItemClickListener onItemClickListener;
    private Context context;
    private int unreadMsg;
    private OnTouchListener onTouchListener;
    private double downX, upX; // 手指滑动的位置
    //    private boolean isMenu = false;
    private SharedPreferences sp;
    private boolean isNews = false;
    private EMMessage lastMessage;
    private String username;
    private EMConversation conversations;
    private boolean isGroup;

    public ConversationRvAdapter(Context context, String username) {
        this.context = context;
        this.username = username;
        sp = context.getSharedPreferences("SystemSetting", Context.MODE_PRIVATE);
        isNews = sp.getBoolean("isAcceptNews", true);
    }

    public void addData(List<EMConversation> datas) {
        this.conversationList = datas;
        this.searchConversationList = datas;
        notifyDataSetChanged();
    }

    @Override
    public ConversationViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
        LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
        View view = inflater.inflate(R.layout.conversation_rv_item, null);
        return new ConversationViewHolder(view);
    }

//    public void setOnItemClickLitener(OnItemClickListener itemClickListener) {
//        this.onItemClickListener = itemClickListener;
//    }
//
//    public void setOnTouchListener(OnTouchListener onTouchListener) {
//        this.onTouchListener = onTouchListener;
//    }

    private EMGroup emGroup;
    private Handler handler;

    private void getGroupName() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    emGroup = EMGroupManager.getInstance().getGroupFromServer(conversations.getUserName());
                    handler.sendEmptyMessage(1);

                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


    @Override
    public void onBindViewHolder(final ConversationViewHolder holder, int position) {
        if (conversationList != null && conversationList.size() > 0) {
            conversations = conversationList.get(position);
            lastMessage = conversations.getLastMessage();
            isGroup = conversations.getIsGroup();

            if (!isGroup) {
//                String friends = lastMessage.getFrom();
//                if (!username.equals(friends)) {
//                    holder.username_Tv.setText(friends);
                holder.username_Tv.setText(conversations.getUserName());
//                } else {
//                    holder.username_Tv.setText(lastMessage.getTo());
//                }
            } else {
//                EMGroup emGroup = null;
//                try {
//                    emGroup = EMGroupManager.getInstance().getGroupFromServer(conversations.getUserName());
//                } catch (EaseMobException e) {
//                    e.printStackTrace();
//                }
//                if (emGroup != null) {

                handler = new Handler(new Handler.Callback() {
                    @Override
                    public boolean handleMessage(Message msg) {
                        switch (msg.what) {
                            case 1:

                                holder.username_Tv.setText(emGroup.getNick());
                                break;
                        }
                        return false;
                    }
                });
                getGroupName();

//                }

            }


            if (isNews) {
                // 获取未读消息数量
                unreadMsg = conversations.getUnreadMsgCount();
                if (unreadMsg > 0) {
                    holder.unreadMsg_Tv.setText(unreadMsg + "");
                    holder.unreadMsg_Tv.setVisibility(View.VISIBLE);
                }
            }
            // 时间转换
            long l = lastMessage.getMsgTime() / 1000;
            String time = l + "";
            holder.chatTime.setText(DataChange.getStandardDate(time));
            // 聊天记录
//            holder.chatContent_Tv.setText(SmileUtils.getSmiledText(
//                    context, EaseCommonUtils.getMessageDigest(lastMessage, this.context)), TextView.BufferType.SPANNABLE);

            TextMessageBody txtReceiveBody = (TextMessageBody) lastMessage.getBody();
            String emojiconName = txtReceiveBody.getMessage();
            if (emojiconName.contains("ee_")) {

                int resId = context.getResources().getIdentifier(emojiconName, "mipmap", context.getPackageName());
                Bitmap bitmap = null;
                bitmap = BitmapFactory.decodeResource(context.getResources(), resId);
                ImageSpan imageSpan = new ImageSpan(context, bitmap);

                SpannableString spannableString =
                        new SpannableString(emojiconName);

                spannableString.setSpan(imageSpan, 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                    if (emojiconName != "delete_expression") {
                holder.chatContent_Tv.setText(spannableString);
//                    }
            } else {
                holder.chatContent_Tv.setText(txtReceiveBody.getMessage());
            }
        }
    }

    @Override
    public int getItemCount() {
        return conversationList != null && conversationList.size() > 0 ? conversationList.size() : 0;
    }

    public class ConversationViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.userAvatar_Iv)
        NetworkImageView userAvatar_Iv;
        @Bind(R.id.username_Tv)
        TextView username_Tv;
        @Bind(R.id.chatContent_Tv)
        TextView chatContent_Tv;
        @Bind(R.id.chatTime)
        TextView chatTime;
        @Bind(R.id.msgHsc)
        HorizontalScrollView msgHsc;
        @Bind(R.id.conversationMenu)
        LinearLayout conversationMenu;
        @Bind(R.id.msg_Rela)
        RelativeLayout msg_Rela;
        @Bind(R.id.unreadMsg_Tv)
        TextView unreadMsg_Tv;

        @Bind(R.id.deleteMsg_Btn)
        Button deleteMsg_Btn;

        @OnClick(R.id.deleteMsg_Btn)
        void deleteMsg() {

        }

        @OnClick(R.id.msg_Rela)
        void intent() {
            String chatFriends = lastMessage.getFrom();
            if (chatFriends.equals(username)) {
                chatFriends = lastMessage.getTo();
            }
            Intent intent = new Intent(context, ChatWindowActivity.class);

            if (!isGroup) {
                intent.putExtra("chattype", 1);
                intent.putExtra("username", chatFriends);
//                Log.d("ConversationViewHolder", conversations.getUserName());

            } else {
                intent.putExtra("chattype", 2);
                if (emGroup != null) {
                    intent.putExtra("groupId", emGroup.getNick());
                    intent.putExtra("groupName", emGroup.getGroupName());
                }
                intent.putExtra("username", conversations.getUserName());
            }

            context.startActivity(intent);
        }

        public ConversationViewHolder(View v) {
            super(v);
            ButterKnife.bind(this, v);
            msg_Rela.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:  //手指按下
                            downX = event.getX(); //获取手指x坐标
//                        if (button != null) {
//                            button.setVisibility(View.GONE);  // 隐藏显示出来的button
//                        }
                            break;
                        case MotionEvent.ACTION_UP:  //手指离开
                            upX = event.getX(); //获取x坐标值
                            break;
                    }

                    if (downX - upX > 100) {
//                        isMenu = true;
                        msgHsc.setMinimumWidth(500);
//                        conversationMenu.setVisibility(View.VISIBLE);
                    }

                    return false;
                }
            });
        }
    }

    /**
     * 过滤器 搜索专用
     */
    public Filter getFilter() {
        if (conversationFilter == null) {
            conversationFilter = new ConversationFilter(conversationList);
        } else {
            conversationFilter.setList(conversationList);
        }
        return conversationFilter;
    }

    private class ConversationFilter extends Filter {
        List<EMConversation> list; // 关键字集合

        public ConversationFilter(List<EMConversation> conversationList) {
            this.list = conversationList;
        }

        public void setList(List<EMConversation> list) {
            this.list = list;
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) { // constraint 限制
            FilterResults results = new FilterResults();

            /**
             * 如果集合为空 建立新集合(节省资源并提高效率)
             * */
            if (list == null) {
                list = new ArrayList<EMConversation>();
            }
            // 结果的长度和内容
            // 若关键字为空和正常消息列表一致
            if (constraint == null || constraint.length() == 0) {
                results.values = searchConversationList;
                results.count = searchConversationList.size();
            } else {
                // 得到关键字
                String constraintString = constraint.toString();
                int count = conversationList.size();
                ArrayList<EMConversation> emConversations = new ArrayList<>();
                // 进行遍历
                for (int i = 0; i < count; i++) {
                    EMConversation value = list.get(i);
                    String username = value.getUserName();

                    // 获取群组或者用户
                    EMGroup group = EMGroupManager.getInstance().getGroup(username);
                    if (group != null) {
                        username = group.getGroupName();
                    } else {
                        EaseUser user = EaseCommonUtils.getUserInfo(username);
                        if (user != null && user.getNick() != null) {
                            username = user.getNick();
                        }
                    }
                    // 如果用户名以关键字开头 添加到结果集合中
                    if (username.startsWith(constraintString)) {
                        emConversations.add(value);
                    } else {
                        // 将用户名以" "分割 并装进数组中(昵称)
                        String[] words = username.split(" ");
                        int wordCount = words.length;

                        // 对数组进行遍历 如果用户名以关键字开头 添加到结果集合中
                        for (int j = 0; j < wordCount; j++) {
                            if (words[j].startsWith(constraintString)) {
                                emConversations.add(value);
                                break;
                            }
                        }
                    }
                }

                results.values = emConversations;
                results.count = emConversations.size();

            }
            return results; // 返回搜索结果
        }

        /**
         * 通过UI线程发布过滤结果
         */
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            if (results.values != null && ((List<EMConversation>) results.values).size() > 0) {
                conversationList.clear();
                conversationList.addAll((List<EMConversation>) results.values);
                notifyDataSetChanged();
            } else {
                notifyDataSetChanged();
            }
        }
    }
}
